package com.xiaohong.goodsWeb.service.impl;

import com.alibaba.fastjson.JSON;
import com.xiaohong.goods.feign.CategoryFeign;
import com.xiaohong.goods.feign.SkuFeign;
import com.xiaohong.goods.feign.SpuFeign;
import com.xiaohong.goods.pojo.Sku;
import com.xiaohong.goods.pojo.Spu;
import com.xiaohong.goodsWeb.service.PageService;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PageServiceImpl implements PageService {

    //静态化模板引擎
    @Autowired
    private TemplateEngine templateEngine;

    //静态化页面保存路径
    @Value("${pagepath}")
    private String pagepath;

    @Autowired
    private SpuFeign spuFeign;

    @Autowired
    private SkuFeign skuFeign;

    @Autowired
    private CategoryFeign categoryFeign;

    //生成静态化页面
    @Override
    public void createPageHtml(String spuId,String token,String selectId,String selectId_spuid) {

        //获取静态页需要的数据
        Map<String, Object> dataMap = buildDataModel(spuId,token,selectId);

        Context context = new Context();
        context.setVariables(dataMap);

        //运行上下文
//        Context context = new Context();

        File file = new File(pagepath);
        if(!file.exists()){
            file.mkdirs();
        }


//        Writer writer = null;
        try(PrintWriter writer = new PrintWriter(file + "/" + selectId_spuid + ".html","UTF-8")) {
//            writer = new PrintWriter(file + "/" + spuId + ".html");

            //处理 开始生成静态化页面
            templateEngine.process("item",context,writer);

        } catch (Exception e) {
            e.printStackTrace();
        }/*finally {
            if(null != writer){
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }*/

    }

    /**
     * 获取静态页需要的数据
     * @param spuId
     * @return
     */
    public Map<String,Object> buildDataModel(String spuId,String token,String selectId){
        Map<String,Object> resultMap = new HashMap<>();
        //查询如下数据

        //2：商品对象(及其下)
        Result result = spuFeign.findAndSkuById(spuId);
        Spu spu = JSON.parseObject(JSON.toJSONString(result.getData()), Spu.class);
        resultMap.put("spu",spu);
        // 被选中sku(默认是第一个)
        Sku selectSku = spu.getSkuList().get(0);

        if(!StringUtils.isEmpty(spu.getSkuList())){
            // 默认是第一个sku的图片
//            resultMap.put("imageList",spu.getSkuList().get(0).getImages().split(","));
            //根据选中id来初始化图片
            List<Sku> skuList = spu.getSkuList();
            for (Sku sku : skuList) {
                if (sku.getId().equals(selectId) ){
                    selectSku = sku;
                    resultMap.put("imageList",sku.getImages().split(","));
                    break;
                }
            }
        }

        resultMap.put("selectSku",selectSku);

        //1:商品分类 一级 二级 三级  名称
        resultMap.put("category1",categoryFeign.findById(spu.getCategory1Id()).getData());
        resultMap.put("category2",categoryFeign.findById(spu.getCategory2Id()).getData());
        resultMap.put("category3",categoryFeign.findById(spu.getCategory3Id()).getData());

        //3: 库存对象集合
//        Sku skuCondition = new Sku();
//        skuCondition.setSpuId(spu.getId());
//        Result<List<Sku>> resultSku = skuFeign.findList(skuCondition);
        resultMap.put("skuList",spu.getSkuList());

        //{"颜色":["深色","蓝色"],"尺码":["27","28","29"]}
        //Map<String,Set<String>> specificationList
        resultMap.put("specificationList",JSON.parseObject(spu.getSpecSkuItems(), Map.class));

        //保存令牌
        resultMap.put("token",token);
        return resultMap;
    }

    /**
     * 删除静态页面
     * @param id
     */
    public void deleteHtml(Long id) {
        try {
            File file = new File(pagepath+"\\" + id + ".html");
            file.deleteOnExit();
        }catch (Exception e){
            throw new RuntimeException("静态资源删除失败或文件不存在！");
        }

    }

    public static void main(String[] args) {
        List list = new ArrayList();
        list.add(1);
        list.add(2);
        list.add(3);
        System.out.println(list.toString());
    }
}
